<template>
  <div class="bg-white rounded-lg p-5 shadow-sm h-full flex flex-col">
    <h2 class="text-lg font-medium mb-4">{{ t("system.overview.alerts") }}</h2>

    <div class="flex-1 flex items-center justify-center">
      <div ref="chartRef" class="w-full h-full"></div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onBeforeUnmount, watch } from "vue";
import { AlertData } from "../../data"; // getMockAlertData
import echarts from "@/plugins/echarts";
import type { EChartsType } from "echarts/core";
import { useI18n } from "@/composables/useI18n";

const { t } = useI18n();

const alertData = ref<AlertData>({ count: 0 }); // getMockAlertData());
const chartRef = ref<HTMLElement>();
let chart: EChartsType | null = null;

// 初始化图表
const initChart = () => {
  if (!chartRef.value) return;

  chart = echarts.init(chartRef.value);

  const option = {
    series: [
      {
        type: "pie",
        radius: ["55%", "90%"], // 加粗圆环：增大内外半径差值
        avoidLabelOverlap: false,
        label: {
          show: false,
          position: "center"
        },
        emphasis: {
          label: {
            show: false
          }
        },
        labelLine: {
          show: false
        },
        data: [
          {
            value: alertData.value.count,
            name: "Alert",
            itemStyle: {
              color: "#ff4d4f",
              borderRadius: 10 // 添加圆角
            }
          },
          {
            value: 12 - alertData.value.count,
            name: "Normal",
            itemStyle: {
              color: "#f0f0f0",
              borderRadius: 10 // 添加圆角
            }
          }
        ]
      }
    ],
    graphic: {
      elements: [
        {
          type: "text",
          left: "center",
          top: "38%",
          style: {
            text: "Alert",
            textAlign: "center",
            fill: "#909399",
            fontSize: 12
          }
        },
        {
          type: "text",
          left: "center",
          top: "50%",
          style: {
            text: alertData.value.count.toString(),
            textAlign: "center",
            fill: "#303133",
            fontSize: 32,
            fontWeight: "bold"
          }
        }
      ]
    }
  };

  chart.setOption(option);
};

// 处理窗口大小变化
const handleResize = () => {
  chart?.resize();
};

// 监听数据变化
watch(
  () => alertData.value,
  () => {
    chart?.dispose();
    initChart();
  },
  { deep: true }
);

onMounted(() => {
  initChart();
  window.addEventListener("resize", handleResize);
});

onBeforeUnmount(() => {
  chart?.dispose();
  window.removeEventListener("resize", handleResize);
});
</script>
